<template>
  <div class="app-container">
    <el-row type="flex" justify="end" class="row-header">
      <el-button type="primary" @click="addFn('0','1')">添加权限</el-button>
    </el-row>
    <el-card>
      <!-- 表格 -->
      <el-table border :data="tableData" row-key="id" default-expand-all>
        <el-table-column align="left" label="权限名称" prop="title" />
        <el-table-column align="center" label="权限标识" prop="code" />
        <el-table-column align="center" label="权限描述" prop="description" />
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <el-button v-if="row.type === '1'" type="text" @click="addFn(row.id,'2')">添加</el-button>
            <el-button type="text" @click="editFn(row.id)">编辑</el-button>
            <el-button type="text" @click="delFn(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 新增/编辑弹窗组件 -->
      <AddDiaLog ref="AddDiaLogRef" :is-show-dialog.sync="isShowDialog" @updateEvent="getPermissionsList" />
    </el-card>
  </div>
</template>

<script>
import AddDiaLog from './components/add-dialog.vue'
import { getPermissions, delPermissions } from '@/api/permissions'
export default {
  components: {
    AddDiaLog
  },
  data() {
    return {
      tableData: [], // 权限列表
      pageConfig: {
        _limit: 5,
        _start: 0
      },
      isShowDialog: false
    }
  },
  created() {
    this.getPermissionsList()
  },
  methods: {
    // 新增
    addFn(id, type) {
      this.isShowDialog = true
      this.$refs.AddDiaLogRef.config = { pid: id + '', type }
    },
    // 编辑
    editFn(id) {
      this.isShowDialog = true
      this.$refs.AddDiaLogRef.title = '编辑'
      // 调用函数，回显数据
      this.$refs.AddDiaLogRef.getPermissionsById(id)
    },
    // 删除
    delFn(id) {
      this.$confirm('确定要删除吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      })
        .then(async() => {
          // 调用删除接口
          await delPermissions(id)
          this.$message.success('删除权限成功')
          // 刷新
          this.getPermissionsList()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 初始化-获取权限列表
    async getPermissionsList() {
      const res = await getPermissions()
      // console.log(res)
      this.tableData = this.listToTree(res.data, '0')
      // console.log('tableData', this.tableData)
    },
    // 格式化权限列表为树形结构
    listToTree(arr, id) {
      // type: '1'表示为一级权限，'2'为二级权限
      const list = []
      arr.forEach((item) => {
        if (Number(item.pid) === Number(id)) {
          // item.children = this.listToTree(arr, item.id)
          item.children = this.listToTree(arr, item.id)
          list.push(item)
        }
      })
      // console.log('list', list)
      return list
    }
  }
}
</script>

<style lang="scss" scoped>
.row-header {
  margin-bottom: 20px;
}
</style>
